package com.hemaapp.yjnh.fragment;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.ViewPagerFragment;
import com.hemaapp.yjnh.activity.LaokeDetailActivity;
import com.hemaapp.yjnh.activity.LoginActivity;
import com.hemaapp.yjnh.activity.ReleaseBlogActivity;
import com.hemaapp.yjnh.activity.WebviewActivity;
import com.hemaapp.yjnh.adapter.LaokeAdapter;
import com.hemaapp.yjnh.adapter.RecyclerTenDecoration;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.listener.OnLaokeClickListener;
import com.hemaapp.yjnh.utils.LoginUtil;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 类描述：
 * 创建人：GuiyouZhang
 * 创建时间：2016/8/2 11:40
 * 修改备注：
 */
public class LaokeListFragment extends ViewPagerFragment implements OnLaokeClickListener {

    private RefreshLoadmoreLayout refreshLoadmoreLayout;
    private RecyclerView recyclerView;
    private ImageView ivEditor;

    private User user;
    private int page = 0;
    private String type = "0";//type=0,1,2对应全部，发布的，参与的
    private String typename = "0";//type=0,1,2,3,4,5,6对应全部,求助,农技,养生,补贴,其他,易货
    private ArrayList<Blog> datas = new ArrayList<>();
    private LaokeAdapter adapter;
    private Blog curBlog;//当前要操作的帖子：删除、点赞、取消赞
    private LoginUtil.LoginCallBack loginCallBack;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_viewpager_laoke);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (savedInstanceState != null) {
            type = savedInstanceState.getString("keytype");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("keytype", type);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void fetchData() {
        getNetWorker().blogList("6", type+","+typename, "4", "1", "", "", "", "", "", "", "", "", "", "", page+"");
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask hemaNetTask) {
        BaseHttpInformation info = (BaseHttpInformation) hemaNetTask
                .getHttpInformation();
        switch (info) {
            case BLOG_LIST:
            case BLOG_SAVEOPERATE:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask hemaNetTask) {
        BaseHttpInformation info = (BaseHttpInformation) hemaNetTask
                .getHttpInformation();
        switch (info) {
            case BLOG_LIST:
            case BLOG_SAVEOPERATE:
                if (!isHidden())
                    cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask, HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case BLOG_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                ArrayList<Blog> blogs = bResult.getObjects();
                if ("0".equals(page)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    datas.clear();
                    datas.addAll(blogs);
                    refreshLoadmoreLayout.setLoadmoreable(true);
                } else {// 更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (bResult.getObjects().size() > 0) {
                        datas.addAll(blogs);
                    } else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                    }
                }
                refreshRecycler();
                break;
            case BLOG_SAVEOPERATE:
                showTextDialog("删除成功");
//                datas.remove(curBlog);
//                refreshRecycler();
                //通知所有界面刷新
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_BLOG);
                EventBus.getDefault().post(msg);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                //1：添加 ;2：取消 ;3：清空
                String oper = netTask.getParams().get("oper");
                int goodcount = 0;
                if (TextUtils.isDigitsOnly(curBlog.getGoodcount())) {
                    goodcount = Integer.parseInt(curBlog.getGoodcount());
                }
                if (oper.equals("1")) {
                    curBlog.setGoodflag("1");// 收藏标记	0未收藏；1收藏
                    goodcount++;
                    View view = getActivity().getLayoutInflater().inflate(R.layout.pop_zan,
                            null);
                    final PopupWindow pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.MATCH_PARENT);
                    pop.setOutsideTouchable(true);
                    pop.setFocusable(true);
                    pop.setBackgroundDrawable(new BitmapDrawable());
                    pop.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            pop.dismiss();
                        }
                    }, 1000);
                } else if (oper.equals("2")) {
                    curBlog.setGoodflag("0");
                    goodcount--;
                }
                curBlog.setGoodcount(goodcount+"");
                refreshRecycler();
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask hemaNetTask, HemaBaseResult hemaBaseResult) {
        BaseHttpInformation information = (BaseHttpInformation) hemaNetTask.getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                XtomToastUtil.showShortToast(getActivity(), "获取数据失败," + hemaBaseResult.getMsg());
                String page = hemaNetTask.getParams().get("page");
                if ("0".equals(page))// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                else
                    refreshLoadmoreLayout.loadmoreFailed();
                break;
            case BLOG_SAVEOPERATE:
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败," + hemaBaseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask hemaNetTask, int i) {
        BaseHttpInformation information = (BaseHttpInformation) hemaNetTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                XtomToastUtil.showShortToast(getActivity(), "获取数据失败,请稍后再试");
                String page = hemaNetTask.getParams().get("page");
                if ("0".equals(page))// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                else
                    refreshLoadmoreLayout.loadmoreFailed();
                break;
            case BLOG_SAVEOPERATE:
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(getActivity(), "操作失败,请稍后再试");
                break;
        }
    }

    @Override
    protected void findView() {
        refreshLoadmoreLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        ivEditor = (ImageView) findViewById(R.id.iv_editor);
    }

    @Override
    protected void setListener() {
        refreshLoadmoreLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().blogList("6", type+","+typename, "4", "1", "", "", "", "", "", "", "", "", "", "", page+"");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().blogList("6", type+","+typename, "4", "1", "", "", "", "", "", "", "", "", "", "", page+"");
            }
        });
        ivEditor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        Intent intent = new Intent(getActivity(), ReleaseBlogActivity.class);
                        intent.putExtra("type", 1);
                        startActivity(intent);
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(getActivity(), loginCallBack);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    public void setType(String type) {
        this.type = type;
    }

    public void refreshData(String typename) {
        if (!isNull(typename))
            this.typename = typename;
        page = 0;
        getNetWorker().blogList("6", type+","+typename, "4", "1", "", "", "", "", "", "", "", "", "", "", page+"");
    }

    private void refreshRecycler() {
        if (adapter == null) {
            adapter = new LaokeAdapter(getActivity(), datas);
            adapter.setClickListener(this);
            adapter.setTypename(typename);
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new RecyclerTenDecoration(getActivity()));
        }else {
            adapter.setTypename(typename);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void OnItemClickListener(Blog blog) {
        Intent itBlog = new Intent(getActivity(), LaokeDetailActivity.class);
        itBlog.putExtra("blog_id", blog.getId());
        startActivity(itBlog);
    }

    @Override
    public void OnZanClickListener(final Blog blog) {
        curBlog = blog;
        loginCallBack = new LoginUtil.LoginCallBack() {
            @Override
            public void onLogin() {
                String oper = "1";//	1：添加 ;2：取消 ;3：清空
                if (blog.getGoodflag().equals("1")) {// 点赞标记	0无 1有
                    oper = "2";
                } else {
                    oper = "1";
                }
                getNetWorker().FolColOperate(user.getToken(), "3", oper, blog.getId());
                loginCallBack = null;
            }
        };
        LoginUtil.getInstance(getActivity(), loginCallBack);
    }

    @Override
    public void OnCommentClickListener(final Blog blog) {
        loginCallBack = new LoginUtil.LoginCallBack() {
            @Override
            public void onLogin() {
                Intent itComment = new Intent(getActivity(), ReleaseBlogActivity.class);
                itComment.putExtra("type", 2);
                itComment.putExtra("blog_id", blog.getId());
                startActivity(itComment);
                loginCallBack = null;
            }
        };
        LoginUtil.getInstance(getActivity(), loginCallBack);
    }

    @Override
    public void OnDeleteClickListener(final Blog blog) {
        curBlog = blog;
        HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
        hbDialog.setText("确定删除?");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                getNetWorker().blogSaveoperate(BaseApplication.getInstance().getUser().getToken(),
                        "1", blog.getId());
            }

        });
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null && !isHidden())
                loginCallBack.onLogin();
        }else if (msg.getType() == EventBusConfig.UPDATE_BLOG
                || msg.getType() == EventBusConfig.UPDATE_REPLY_ADD
                || msg.getType() == EventBusConfig.UPDATE_REPLY_REMOVE) {
            refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
        }
    }
}
